import Vue from 'vue'
import Vuex from 'vuex'
import {setItem,removeItem,getItem} from '../util/common.js'
Vue.use(Vuex);//vue的插件机制

//Vuex.Store 构造器选项
const store = new Vuex.Store({
	state:{//存放状态
		"mycart":getItem('mycart')||[],
		"userinfo":getItem('userinfo')||{},
		"token":getItem('token')||''
		// typeof(getItem('mycart'))=='string'?JSON.parse(getItem('mycart')):getItem('mycart')||[]
	},
	mutations:{
		login(){},
		// 添加购物车
		addcart(state,item){
			let itemidx=state.mycart.findIndex(theitem=>theitem.goods_id==item.goods_id)
			if(itemidx<0){
				state.mycart.push(item)
			}else{
				state.mycart[itemidx].goods_count+=1
			}
			setItem('mycart',state.mycart)
		},
		//修改购物车数量
		chcartnum(state,item){
			let itemidx=state.mycart.findIndex(theitem=>theitem.goods_id==item.goods_id);
			state.mycart[itemidx].goods_count=item.goods_count
			setItem('mycart',state.mycart)
		},
		//勾选和取消勾选购物车
		seCheckbox(state,item){
			let itemidx=state.mycart.findIndex(theitem=>theitem.goods_id==item.goods_id);
			state.mycart[itemidx].goods_state=item.goods_state
			setItem('mycart',state.mycart)
		},
		// 批量勾选购物车和取消勾选购物车
		seAllCheckbox(state,boolen){
			state.mycart.forEach((item,index,arr)=>arr[index].goods_state=boolen);
			setItem('mycart',state.mycart)
		},
		// 移除购物车
		removecart(state,index){
			state.mycart.splice(index,1)
			setItem('mycart',state.mycart)
		},
		// 清空购物车
		removeall(state){
			removeItem('mycart')
		},
		//设置token
		setToken(state,token){
			state.token=token;
			setItem('token',token)
		},
		//更新用户信息
		updateUserInfo(state,info){
			state.userinfo=info;
			setItem('userinfo',info)
		},
		// 退出登录
		outLogin(state){
			state.userinfo={}
			state.token=''
			removeItem('userinfo')
			removeItem('token')
		}
	},
	getters: {
		totle(state){
			let totle=0
			if(state.mycart.length){
				state.mycart.forEach((item)=>{
					totle+=item.goods_count
				})
			}else{
				totle=0
			}
			
			return totle
		},
		totlepay(state){
			let totle=0
			if(state.mycart.length){
				state.mycart.forEach((item)=>{
					if(item.goods_state){
						totle+=item.goods_count*item.goods_price
					}
				})
			}else{
				totle=0
			}
			
			return totle
		}
		
	},
	
})
export default store